package lottery

import (
	"aquaman/app/biz/lottery/model"
	"aquaman/app/infra/ecode"
	utils_strings "aquaman/app/utils/strings"
	"io"
	"os"
	"strconv"
	"strings"
	"encoding/json"
	"fmt"
	"github.com/mitchellh/mapstructure"
	"github.com/pkg/errors"
	"io/ioutil"
	"net/http"

)

const (
	ssq_host = "http://www.cwl.gov.cn/cwl_admin/kjxx/findDrawNotice?name=ssq&issueCount=1"
	dlt_host = "https://webapi.sporttery.cn/gateway/lottery/getDigitalDrawInfoV1.qry?param=85,0&isVerify=1"
)

type SpiderSSQ struct {
	// 名字
	Name string 		`json:"name"`
	// 期数
	Code string		`json:"code"`
	// 开奖日期
	Date string			`json:"date"`
	// 星期几
	Week string 		`json:"week"`
	// 红球
	Red  string			`json:"red"`
	// 蓝球
	Blue string			`json:"blue"`
	Blue2 string 		`json:"blue2"`
	// 本期销量
	Sales string 		`json:"sales"`
	// 累计奖池
	PoolMoney string 	`json:"poolMoney" db:"pool_money"`
	// 中奖详情简单
	Content string		`json:"content"`
	// 中奖详情详细
	Prizegrades []Prizegrade	`json:"prizegrades"`
}

type Prizegrade struct {
	Type string			`json:"type"`
	Typenum string		`json:"typenum"`
	Typemoney string	`json:"typemoney"`
}

type SpiderDLT struct {
	LotteryDrawNum 			string
	LotteryDrawResult 		string
	LotteryDrawTime			string
	PoolBalanceAfterdraw	string
	DrawPdfUrl				string
}


type Spider struct {
	client *http.Client
}

func NewSpider() *Spider {
	return &Spider{
		client: &http.Client{},
	}
}
func (spider *Spider)FetchSSQ()(lottery model.Lottery) {
	//client := &http.Client{}
	//q := url.Values{}
	//q.Set("name", "ssq")
	//q.Set("issueCount", "1")
	//req, err := http.NewRequest(http.MethodGet, ssq_host+q.Encode(), nil)
	req, err := http.NewRequest(http.MethodGet, ssq_host, nil)
	if err != nil{
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口格式错误"))
	}
	req.Header.Set("Referer", "http://www.cwl.gov.cn/")
	resp, err := spider.client.Do(req)
	if err != nil {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口发生问题"))
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口发生问题"))
	}
	var data map[string]interface{}
	err = json.Unmarshal(body, &data)
	if err != nil { errors.Wrap(ecode.LotterySpiderError,"爬虫接口数据解析失败") }
	resultList, isOK := data["result"].([]interface{})
	if !isOK {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口数据格式错误"))
	}
	if len(resultList) > 0 {
		var ssq SpiderSSQ
		result := resultList[0]
		err = mapstructure.Decode(result, &ssq)
		if err != nil { errors.Wrap(ecode.LotterySpiderError,"爬虫接口数据解析失败") }
		lottery.Code,_ = strconv.ParseInt(ssq.Code,10,64)
		var (
			date        string
			firstCount  int64
			firstMoney  float64
			secondCount int64
			secondMoney float64
			thirdCount  int64
			thirdMoney  float64
		)
		if len(ssq.Date) > 10 {
			date = utils_strings.Substr(ssq.Date,0,10)
		}
		if len(ssq.Prizegrades) >= 3 {
			firstCount,_ = strconv.ParseInt(ssq.Prizegrades[0].Typenum,10,64)
			firstMoney,_ = strconv.ParseFloat(ssq.Prizegrades[0].Typemoney,64)
			secondCount,_ = strconv.ParseInt(ssq.Prizegrades[1].Typenum,10,64)
			secondMoney,_ = strconv.ParseFloat(ssq.Prizegrades[1].Typemoney,64)
			thirdCount,_ = strconv.ParseInt(ssq.Prizegrades[2].Typenum,10,64)
			thirdMoney,_ = strconv.ParseFloat(ssq.Prizegrades[2].Typemoney,64)
		}
		lottery.Date = date
		lottery.Red = ssq.Red
		if len(ssq.Blue2) > 0 {
			lottery.Blue =  fmt.Sprintf("%s,%s",ssq.Blue,ssq.Blue2)
		}else {
			lottery.Blue =  ssq.Blue
		}
		lottery.Sales,_ =  strconv.ParseFloat(ssq.Sales,64)
		lottery.PoolMoney,_ = strconv.ParseFloat(ssq.PoolMoney,64)
		lottery.FirstCount = firstCount
		lottery.FirstMoney = firstMoney
		lottery.SecondCount = secondCount
		lottery.SecondMoney = secondMoney
		lottery.ThirdCount = thirdCount
		lottery.ThirdMoney = thirdMoney
		lottery.Content = ssq.Content
	}else {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口数据返回为空"))
	}
	return
}


func (spider *Spider)FetchDLT() (lottery model.Lottery) {

	client := &http.Client{}
	req, err := http.NewRequest(http.MethodGet, dlt_host, nil)
	if err != nil {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口格式错误"))
	}
	resp, err := client.Do(req)
	if err != nil {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口发生问题"))
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口解析错误"))
	}
	var result map[string]interface{}
	err = json.Unmarshal(body, &result)
	if err != nil {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口解析错误"))
	}
	value,isOK := result["value"].(map[string]interface{})
	if !isOK {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口解析错误"))
	}
	d,isOK := value["dlt"].(map[string]interface{})
	if !isOK {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口解析错误"))
	}
	var dlt SpiderDLT
	err = mapstructure.Decode(d, &dlt)
	if err != nil {
		panic(errors.Wrap(ecode.LotterySpiderError,"爬虫接口解析错误"))
	}
	code,_ := strconv.ParseInt(fmt.Sprintf("20%s",dlt.LotteryDrawNum),10,64)
	date := strings.Split(dlt.LotteryDrawTime," ")[0]
	balls := strings.Split(dlt.LotteryDrawResult," ")
	redBalls := balls[0:5]
	blueBalls := balls[5:7]
	red := strings.Join(redBalls,",")
	blue := strings.Join(blueBalls,",")
	poolMoney,_ := strconv.ParseFloat(strings.ReplaceAll(dlt.PoolBalanceAfterdraw,",",""),64)
	lottery.Content = dlt.DrawPdfUrl
	lottery.Code = code
	lottery.Date = date
	lottery.Red = red
	lottery.Blue = blue
	lottery.PoolMoney = poolMoney
	//if len(lottery.Content) > 0 {
	//	if err = DownloadFile("dlt.pdf", lottery.Content); err != nil {
	//		panic(errors.Wrap(err,"pdf解析错误"))
	//	}
	//
	//}



	return
}

// DownloadFile will download a url to a local file. It's efficient because it will
// write as it downloads and not load the whole file into memory.
func DownloadFile(filepath string, url string) error {
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Create the file
	out, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer out.Close()

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	return err
}


